import 'package:finance_app/src/websocket/web_socket.dart';
import 'package:flutter/material.dart';

typedef T Selector<T>(WebSocketProvide provide);
typedef bool ShouldRebuild<T>(T p, T n);

typedef Widget WebSocketWidgetBuilder<T>(T t);

class WebSocketWidget<T> extends StatefulWidget {
  final Selector<T> selector;
  final WebSocketWidgetBuilder<T> builder;
  final T initialValue;
  final ShouldRebuild<T> shouldRebuild;

  const WebSocketWidget(
      {Key key,
      this.initialValue,
      @required this.selector,
      @required this.builder,
      this.shouldRebuild})
      : super(key: key);

  @override
  _WebSocketWidgetState<T> createState() => _WebSocketWidgetState<T>();
}

class _WebSocketWidgetState<T> extends State<WebSocketWidget<T>> {
  T t;

  WebSocketProvide provide;
  VoidCallback listener;

  @override
  void initState() {
    super.initState();
    t = widget.initialValue;
    WebSocketProvide.getInstance().then((value) {
      provide = value;
      t = widget.selector(value);
      if (mounted) setState(() {});
      listener = () {
        if (widget.shouldRebuild != null) {
          if (widget.shouldRebuild(t, widget.selector(value))) {
            t = widget.selector(value);
            if (mounted) setState(() {});
          }
        } else if (t != widget.selector(value)) {
          t = widget.selector(value);
          if (mounted) setState(() {});
        }
      };
      value.addListener(listener);
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (listener != null) provide?.removeListener(listener);
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(t);
  }
}
